<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script type="text/javascript" src="../js/vue-2.6.12.js"></script>
<div id="app">
    <my_table :users="users" @to_update="to_update"></my_table>
    <my_form :user="user" @emit_update="to_show"></my_form>
</div>
<template id="my_table">
    <table border="1">
        <tr><td>编号</td><td>姓名</td><td>年龄</td><td>操作</td></tr>
        <tr v-for="(user,index) in users" :key="index"><td>{{user.id}}</td><td>{{user.name}}</td>
            <td>{{user.age}}</td>
            <td><button @click="emitUpdate(index)">更新</button></td>
        </tr>
    </table>
</template>
<template id="my_form">
    <form action="" @submit.prevent="emit_update">
        姓名:<input type="text" v-model="user.name"/>
        年龄:<input type="text" v-model="user.age"/>
        <button>提交</button>
    </form>
</template>
<script>
    const my_table={
        template:"#my_table",
        props:["users"],
        methods:{
            emitUpdate(index){
                this.$emit("to_update",JSON.parse(JSON.stringify(this.users[index])));
            }
        }
    };
    const my_form={
        template:"#my_form",
        props:["user"],
        methods:{
            emit_update(){
                //把user对象传递给父组件
                this.$emit("emit_update",JSON.parse(JSON.stringify(this.user)));
            }
        }
    }
    const vm = new Vue({
        el:"#app",
        data:{
            users:[{id:1,name:"zhangsan",age:20},{id:2,name:"lisi",age:20}],
            user:{}
        },
        components:{
            my_table,
            my_form
        },
        methods:{
            to_update(user){
                this.user=user;
                console.log(this.user)
            },
            to_show(user){
                //把user放入到user集合里面
                this.users.forEach((u,index)=>{
                    if(u.id==user.id){
                        //this.users[index]=user;
                        this.$set(this.users,index,user);
                    }
                })
            }
        }
    })
</script>
</body>
</html>